﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using OnlineStore.Data;
using OnlineStore.Models;

namespace OnlineStore.Services.Support
{
    public class CartService : ICartService
    {
        private readonly OnlineStoreDbContext _context;

        public CartService(OnlineStoreDbContext context)
        {
            _context = context;
        }

        public IEnumerable<ProductInCart> GetProductInCart(int userId)
        {
            var cart = _context.Carts
                .Include(c => c.ProductInCarts)
                .ThenInclude(pc => pc.Product)
                .FirstOrDefault(c => c.UserId == userId);
            Debug.Assert(cart != null);
            return cart.ProductInCarts;
        }

        public async Task UpdateQuantityAsync(int productId, int quantity)
        {
            var productInCart = _context.ProductInCarts
                .FirstOrDefault(pc => pc.ProductId == productId);

            Debug.Assert(productInCart != null);

            productInCart.Quantity = quantity;
            await _context.SaveChangesAsync();
        }

        public async Task RemoveProduct(int productId)
        {
            var productInCart = _context.ProductInCarts
                .FirstOrDefault(pc => pc.ProductId == productId);

            Debug.Assert(productInCart != null);
            _context.Remove(productInCart);
            await _context.SaveChangesAsync();
        }
    }
}